
<template>
  <div class="EmergencyList">
    <LsdDialog :dialogConfig="dialogConfig" @handleBtn="handleBtn" @close="handleClose">
      <DialogForm ref="formComponent" slot="dialog" :formConfig="formConfig" @changeEvent="changeSelected"></DialogForm>
      <LsdDialogTitle slot="dialog" :titleConfig="titleConfig" :activeNames="activeNames">
        <div slot="slot1">
          <el-table :data="taiqu_table" border style="width: 100%"
            :header-cell-style="{ background: '#B1C8F9', color: '#000000', border: '1px solid #ccc' }">
            <el-table-column prop="lineName" label="停运台区名称" width="180" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.lineCode" placeholder="请选择"
                  @change="v => changeTaiquName(v, scope.row, scope.$index)" :name="`${scope.$index}`" size="small"
                  popper-class="tingdian-add-popper" :popper-append-to-body="false">
                  <el-option v-for="(item, i) in taiqu_options" :key="i" :label="item.lineName" :value="item.lineCode">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="所属单位" width="180" align="center">
            </el-table-column>
            <el-table-column prop="location" label="位置" align="left">
            </el-table-column>
            <el-table-column prop="blackoutTime" label="停电时间" align="center">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.blackoutTime" type="datetime" placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" size="small" :picker-options="pickerOptions">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column prop="recoverTime" label="复电时间" align="center">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.recoverTime" type="datetime" placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" size="small"
                  @change="(val) => { pickerChange(val, scope, 1) }">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <!-- <el-button type="text" icon="el-icon-plus" size="small" @click="addTaiquRow"
                  v-if="scope.$index == taiqu_table.length - 1">
                </el-button>
                <el-button type="text" icon="el-icon-minus" size="small" @click="taiqu_table.splice(scope.$index, 1)"
                  v-if="taiqu_table.length > 1">
                </el-button> -->
                <img src="../../../../assets/img/listAdd.png" alt=""
                  style="width: 16px; height: 16px; cursor: pointer; margin-right: 5px" @click="addTaiquRow(scope.$index)"
                  v-if="scope.$index == taiqu_table.length - 1">
                <img src="../../../../assets/img/listReduc.png" alt=""
                  style="width: 16px; height: 16px; cursor: pointer; margin-right: 5px"
                  @click="taiqu_table.splice(scope.$index, 1)" v-if="taiqu_table.length > 1">
              </template>
            </el-table-column>
          </el-table>
          <div style="font-size: 16px; font-weight: 700; color: #333; margin-top: 5px;">总计：{{ getTaiquTableLength }} 条
          </div>
        </div>
        <div slot="slot2">
          <el-table :data="zyyh_table" border style="width: 100%"
            :header-cell-style="{ background: '#B1C8F9', color: '#000000', border: '1px solid #ccc' }">
            <el-table-column prop="lineName" label="停电重要用户" width="180" align="center">
              <template slot-scope="scope">
                <el-select :ref="`taiqu_select_${scope.$index}`" v-model="scope.row.lineCode" placeholder="请选择"
                  @change="v => changeZyyhName(v, scope.row, scope.$index)" :name="`${scope.$index}`" size="small"
                  popper-class="tingdian-add-popper" :popper-append-to-body="false">
                  <el-option v-for="(item, i) in zyyh_options" :key="i" :label="item.lineName" :value="item.lineCode">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="grade" label="客户等级" width="180" align="center">
            </el-table-column>
            <el-table-column prop="unitName" label="所属单位" width="100" align="center">
            </el-table-column>
            <el-table-column prop="location" label="位置" align="left">
            </el-table-column>
            <el-table-column prop="blackoutTime" label="停电时间" align="center">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.blackoutTime" type="datetime" placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" size="small" :picker-options="pickerOptions">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column prop="recoverTime" label="复电时间" align="center">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.recoverTime" type="datetime" placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" size="small"
                  @change="(val) => { pickerChange(val, scope, 2) }">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <!-- <el-button type="text" icon="el-icon-plus" size="small" @click="addZyyhRow"
                  v-if="scope.$index == zyyh_table.length - 1">
                </el-button>
                <el-button type="text" icon="el-icon-minus" size="small" @click="zyyh_table.splice(scope.$index, 1)"
                  v-if="zyyh_table.length > 1">
                </el-button> -->
                <img src="../../../../assets/img/listAdd.png" alt=""
                  style="width: 16px; height: 16px; cursor: pointer; margin-right: 5px" @click="addZyyhRow(scope.$index)"
                  v-if="scope.$index == zyyh_table.length - 1">
                <img src="../../../../assets/img/listReduc.png" alt=""
                  style="width: 16px; height: 16px; cursor: pointer; margin-right: 5px"
                  @click="zyyh_table.splice(scope.$index, 1)" v-if="zyyh_table.length > 1">
              </template>
            </el-table-column>
          </el-table>
          <div style="font-size: 16px; font-weight: 700; color: #333; margin-top: 5px;">总计：{{ getZyyhTableLength }} 条
          </div>
        </div>
        <div slot="slot3">
          <el-table :data="ptyh_table" border style="width: 100%"
            :header-cell-style="{ background: '#B1C8F9', color: '#000000', border: '1px solid #ccc' }">
            <el-table-column prop="blackoutCount" label="停电数量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.blackoutCount" type="number" placeholder="请输入内容" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="recoverCount" label="恢复供电数量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.recoverCount" type="number" placeholder="请输入内容" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="recoverRatio" label="恢复率" align="center">
              <template>
                {{ recoverRatio }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </LsdDialogTitle>
    </LsdDialog>
  </div>
</template>

<script>
import {
  // getTqOptionsApi,
  // getZyyhOptionsApi,
  getLineOptionsApi,
  submitApi,
  emergencyOutagelnformationApi
} from "@/api/EmergencyDisposal/tdxxfb.js";
import { getpublishedinfo } from "@/api/EmergencyDisposal/xymld.js";
import { showTime } from "@/lib";
const tq = {
  type: "tq",
  blackoutTime: "",
  grade: "",
  id: "",
  lineCode: "",
  lineName: "",
  location: "",
  recoverTime: "",
  specialtyCode: "",
  specialtyName: "",
  unitId: "",
  unitName: "",
  voltageClasses: ""
};
const zyyh = {
  type: "zyyh",
  blackoutTime: "",
  grade: "",
  id: "",
  lineCode: "",
  lineName: "",
  location: "",
  recoverTime: "",
  specialtyCode: "",
  specialtyName: "",
  unitId: "",
  unitName: "",
  voltageClasses: ""
};
export default {

  name: "Submitted",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      eventIds: "",
      // 弹窗表单信息
      formConfig: {
        formData: [
          {
            type: "input",
            label: "报送单位",
            prop: "unitName",
            dic: "dic_bsdw",
            class: "half",
            lableWidth: "140px",
            isShow: true,
            option: [],
            isDisabled: true
          },
          {
            type: "input",
            label: "报送部门",
            prop: "createDeptName",
            dic: "dic_bsbm",
            class: "half",
            lableWidth: "140px",
            isShow: true,
            option: [],
            isDisabled: true
          },
          {
            type: "input",
            label: "填报人",
            prop: "creator",
            class: "half",
            lableWidth: "140px",
            isDisabled: true
          },
          {
            type: "input",
            label: "填报时间",
            prop: "createTime",
            class: "half",
            dateType: "datetime",
            lableWidth: "140px",
            isDisabled: true
          },
          {
            type: "select",
            label: "响应命令单",
            prop: "responseId",
            name: "responseName",
            class: "sjgy",
            lableWidth: "140px",
            option: []
          }
        ],
        rules: {
          responseId: [
            { required: true, message: "请选择响应命令单", trigger: "change" }
          ]
        }
      },
      activeNames: ["1", "2", "3"], // 折叠面板默认展开列
      // 折叠面板信息
      titleConfig: [
        {
          title: "台区",
          name: "1",
          slot: "slot1"
        },
        {
          title: "重要用户",
          name: "2",
          slot: "slot2"
        },
        {
          title: "普通用户",
          name: "3",
          slot: "slot3"
        }
      ],
      // 弹窗信息
      dialogConfig: {
        title: "停复电信息报送单",
        isShow: false, // 弹窗显示隐藏
        btnList: [
          {
            name: "提交",
            id: "Submit", // 事件名
            type: "primary",
            size: "small"
          },
          {
            name: "返回",
            id: "cancel",
            size: "small"
          }
        ]
      },
      taiqu_options: [],
      taiqu_table: [JSON.parse(JSON.stringify(tq))], // 台区数据
      zyyh_options: [],
      zyyh_table: [JSON.parse(JSON.stringify(zyyh))], // 重要用户数据
      ptyh_table: [{
        blackoutCount: "",
        recoverCount: "",
        recoverRatio: ""
      }],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now(); // 如果没有后面的-8.64e6就是不可以选择今天的
        }
      }
    };
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          // this.getinfo()
          this.getPublishedResponse();
          this.dialogConfig.isShow = true;

          this.$nextTick(() => {
            this.$set(this.$refs.formComponent.form, "creator", this.getCreator.name);
            this.$set(this.$refs.formComponent.form, "unitName", this.getCreator.dept);
            // this.$set(this.$refs.formComponent.form, "createTime", new Date().toLocaleString().replace(/\//g, "-"))
            this.$set(this.$refs.formComponent.form, "createDeptName", JSON.parse(sessionStorage.getItem("org")).ssbmName);
            this.$set(this.$refs.formComponent.form, "createTime", showTime(new Date()));
          });
        } else {
          if (this.dialogConfig.isShow) {
            this.dialogConfig.isShow = false;
            this.$emit("list");
            this.cancel();
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  components: {},

  computed: {
    // 恢复率计算
    recoverRatio() {
      const { blackoutCount, recoverCount } = this.ptyh_table[0];
      let recoverRatio = "";
      console.log(recoverCount, blackoutCount);
      if (blackoutCount && recoverCount) {
        if (parseFloat(recoverCount) > parseFloat(blackoutCount)) {
          this.$message.error("恢复供电数不可大于停电数");
          recoverRatio = "";
        } else {
          recoverRatio = `${((recoverCount / blackoutCount) * 100).toFixed(2)}%`;
        }
      }
      // this.ptyh_table[0].recoverRatio = recoverRatio
      return recoverRatio;
    },
    getCreator() {
      const account = sessionStorage.getItem("account");
      const org = sessionStorage.getItem("org");
      const creator = {
        name: (account && JSON.parse(account).realName) || "",
        unit: (org && JSON.parse(org).unitName) || "",
        dept: (org && JSON.parse(org).orgName) || "",
        unitName: (org && JSON.parse(org).unitName) || ""
      };
      return creator;
    },
    getTaiquTableLength() {
      let num = 0;
      this.taiqu_table.forEach(item => {
        if (item.lineCode) {
          num++;
        }
      });
      return num;
    },
    getZyyhTableLength() {
      let num = 0;
      this.zyyh_table.forEach(item => {
        if (item.lineCode) {
          num++;
        }
      });
      return num;
    }

  },
  created() {
    this.getTingdianOptions();
  },
  methods: {
    pickerChange(val, scope, type) {
      if (type == 1) {
        const start = +new Date(this.taiqu_table[scope.$index].blackoutTime);
        const end = +new Date(val);
        if (start > end || !start) {
          this.taiqu_table[scope.$index].recoverTime = "";
          const message = start ? "复电时间不能早于停电时间" : "请先选择停电时间";
          this.$message.warning(message);
        }
      } else if (type == 2) {
        const start = +new Date(this.zyyh_table[scope.$index].blackoutTime);
        const end = +new Date(val);
        if (start > end || !start) {
          this.zyyh_table[scope.$index].recoverTime = "";
          const message = start ? "复电时间不能早于停电时间" : "请先选择停电时间";
          this.$message.warning(message);
        }
      }

    },
    // 获取已发布的响应命令单
    getPublishedResponse() {
      getpublishedinfo({}).then(res => {
        console.log(res, "-------------------res----");
        let options = [];
        options = res.map(item => {
          return {
            label: item.responseName,
            value: item.id,
            ...item
          };
        });
        this.formConfig.formData[4].option = options;
        console.log("options", options);
        if (options.length) {
          const { value } = options[0];
          this.eventIds = value;
        }
      });
    },
    // 获取响应命令单关联的灾情信息
    async emergencyOutagelnformation(eventIds) {
      try {
        const res = await emergencyOutagelnformationApi({ eventIds });
        console.log("---------res", res);
        const ptyh = res?.ptyh?.[0];
        this.ptyh_table = ptyh ? [{
          blackoutCount: ptyh.blackoutCount,
          recoverCount: ptyh.recoverCount,
          recoverRatio: ptyh.recoverRatio
        }] : [{
          blackoutCount: "",
          recoverCount: "",
          recoverRatio: ""
        }];
        this.taiqu_table = res.tq || [JSON.parse(JSON.stringify(tq))];
        this.zyyh_table = res.zyyh || [JSON.parse(JSON.stringify(zyyh))];
      } catch (error) {
        console.log(error);
      }
    },
    changeSelected(val, item) {
      console.log(item, "????item");
      let eventIds = "";
      item.option.map(i => {
        if (i.id === val) {
          eventIds = i.emergencyEventIds;
        }
      });
      this.emergencyOutagelnformation(eventIds);
    },
    // 获取线路数据
    getTingdianOptions() {
      getLineOptionsApi({ specialtyCode: "tq" }).then(res => {
        this.taiqu_options = res;
      });
      getLineOptionsApi({ specialtyCode: "zyyh" }).then(res => {
        this.zyyh_options = res;
      });
    },
    handleClose() {
      this.$refs.formComponent.form = this.$refs.formComponent.$options.data().form;
      this.taiqu_table = [JSON.parse(JSON.stringify(tq))]; // 台区数据
      this.zyyh_table = [JSON.parse(JSON.stringify(zyyh))]; // 重要用户数据
      this.ptyh_table = [{
        blackoutCount: "",
        recoverCount: "",
        recoverRatio: ""
      }];
      this.$refs.formComponent.resetFields();
      this.$emit("update:dialogVisible", false);
    },
    handleBtn(item) {
      this[item.id]();
    },
    Submit() {
      this.$refs.formComponent.isValidate();
      if (!this.$refs.formComponent.flag) return;
      const { blackoutCount, recoverCount } = this.ptyh_table[0];
      if (!blackoutCount) {
        this.$message.error("请输入停电数");
        return;
      }
      if (!recoverCount) {
        this.$message.error("请输入恢复供电数");
        return;
      }
      if (parseFloat(recoverCount) > parseFloat(blackoutCount)) {
        this.$message.error("恢复供电数不可大于停电数");
        return;
      }


      this.ptyh_table[0].recoverRatio = this.recoverRatio;
      const taiqu_table = this.taiqu_table;
      // taiqu_table.map(i => {
      //   i.type = "tq";
      // });
      const zyyh_table = this.zyyh_table;
      // zyyh_table.map(i => {
      //   i.type = "zyyh";
      // });


      const params = {
        ...this.$refs.formComponent.form,
        tq: taiqu_table[0].lineCode ? taiqu_table : null,
        zyyh: zyyh_table[0].lineCode ? zyyh_table : null,
        // ptyh: this.ptyh_table
        ...this.ptyh_table[0],
        modifyTime: showTime(new Date())
      };
      submitApi(params).then(res => {
        this.handleClose();
      });
    },
    cancel() {
      this.$emit("update:dialogVisible", false);
    },
    // 添加台区数据
    addTaiquRow(val) {
      if (this.taiqu_table[val].lineCode) {
        this.taiqu_table.push(JSON.parse(JSON.stringify(zyyh)));
      } else {
        this.$message.warning("请填写当前行");
      }
    },
    // 选择台区
    changeTaiquName(val, row, i) {
      const filter = this.taiqu_options.filter(item => item.lineCode == val);
      const obj = {
        unitName: filter[0].unitName,
        location: filter[0].location
      };
      this.taiqu_table[i] = Object.assign(this.taiqu_table[i], obj);
    },
    // 选择重要用户
    changeZyyhName(val, row, i) {
      const filter = this.zyyh_options.filter(item => item.lineCode == val);
      const obj = {
        unitName: filter[0].unitName,
        location: filter[0].location,
        grade: filter[0].grade
      };
      this.zyyh_table[i] = Object.assign(this.zyyh_table[i], obj);
    },
    addZyyhRow(val) {
      if (this.zyyh_table[val].lineCode) {
        this.zyyh_table.push(JSON.parse(JSON.stringify(zyyh)));
      } else {
        this.$message.warning("请填写当前行");
      }

    }

  }
};

</script>
<style lang='less' scoped>@import "../../../../assets/style/common.less";
@import "../../../../assets/style/ComponentStyle.less";
@import "../../../../assets/style/pop-upNotification.less";

:deep(.el-form-item__label) {
  font-size: 16px;
}</style>
